package com.zkingsoft.actions.visitor;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.constance.Dictionary;
import com.zkingsoft.constance.SystemConstance;
import com.zkingsoft.model.Users;
import com.zkingsoft.plugin.message.Sendsms;
import com.zkingsoft.plugin.util.EncrypUtil;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.BusParamService;
import com.zkingsoft.services.UsersService;

/**
 * 
 * @Description: 不需要登录可以访问的action
 * @author:姜友瑶
 * @date 2016年8月31日
 */
@Controller
@RequestMapping(value = "/visitor")
public class VisitorController extends BaseController {

	@Resource
	private UsersService userService;
	@Resource
	private BusParamService busParamService;

	/**
	 * 
	 * @Description: 页面定向方法，每个权限模块公用一个，每个模块共享一个一级路径，已便于进行权限过滤
	 * @author:姜友瑶
	 * @param page1
	 * @param page2
	 * @return 返回类型 String
	 * @date 2016年8月31日
	 */
	@RequestMapping(value = "/redirect/{page1}/{page2}")
	public String redirect(@PathVariable("page1") String page1, @PathVariable("page2") String page2) {
		return "visitor/" + page1 + "/" + page2;
	}

	@RequestMapping(value = "/redirect/{page1}")
	public String redirect(@PathVariable("page1") String page1) {
		return "visitor/" + page1;
	}

	/**
	 * 手机注册获取验证码
	 */
	@RequestMapping(value = "/getCode")
	public @ResponseBody AjaxResult register(String phone) {
		if (!userService.isOnlyPhone(phone)) { // 判断手机号是否已注册
			try {
				WebUtil.getSession().setAttribute(Dictionary.YZM, Sendsms.sendSms(phone)); // 获取验证码
				// WebUtil.getSession().setAttribute(Dictionary.YZM, "1234");
				WebUtil.getSession().setAttribute(Dictionary.SJ, phone); // 获取发送验证码的手机号
				WebUtil.getSession().setMaxInactiveInterval(60);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return new AjaxResult(AjaxResult.STATUS_OK, null, null);
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "手机号已注册");
		}
	}

	/**
	 * 手机找密码发送验证码
	 */
	@RequestMapping(value = "/getCode1")
	public @ResponseBody AjaxResult getCode1(String tel) {
		if (userService.isOnlyPhone(tel)) {
			try {
				WebUtil.getSession().setAttribute(Dictionary.YZM, Sendsms.sendSms(tel)); // 获取到验证码
				// WebUtil.getSession().setAttribute(Dictionary.YZM, "1234");
				// //获取到验证码
				WebUtil.getSession().setAttribute(Dictionary.SJ, tel); // 获取到手机号
				WebUtil.getSession().setMaxInactiveInterval(60 * 10); // 10分钟失效
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return new AjaxResult(AjaxResult.STATUS_OK, null, null);
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "手机号未注册");
		}
	}

	/**
	 * 手机找回密码
	 */
	@RequestMapping(value = "/findByPhone")
	public @ResponseBody AjaxResult findByPhone(Users user) {
		if (WebUtil.getSession().getAttribute(Dictionary.YZM) != null) { // 判断验证码是否失效
			if (user.getTel().equals(WebUtil.getSession().getAttribute(Dictionary.SJ))) { // 判断手机号是否为发送短信的手机
				if (!(WebUtil.getRequest().getParameter("code"))
						.equals(WebUtil.getSession().getAttribute(Dictionary.YZM))) {// 判断验证码是否正确
					return new AjaxResult(AjaxResult.STATUS_ERR, null, "验证码错误!");
				} else {
					Users userQuery = new Users();
					userQuery.setTel(user.getTel());
					List<Users> vipInfo = userService.findByModel(userQuery);
					if (vipInfo.size() > 0) {
						try {
							if (vipInfo.get(0).getPassword() != null) {// 判断密码是否为空
								if (vipInfo.get(0).getPassword().equals(EncrypUtil.getMD5(user.getPassword()))) {// 判断更改密码和原密码是否相同
									return new AjaxResult(AjaxResult.STATUS_ERR, null, "新密码和原密码相同");
								}
							}
							vipInfo.get(0).setPassword(EncrypUtil.getMD5(user.getPassword()));
							int i = userService.modify(vipInfo.get(0));
							if (i > 0) {
								return new AjaxResult(AjaxResult.STATUS_OK, null, "更改成功");
							} else {
								return new AjaxResult(AjaxResult.STATUS_ERR, null, "更改失败");
							}
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					} else {
						return new AjaxResult(AjaxResult.STATUS_ERR, null, "用户信息异常");
					}
				}
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "手机未验证");
			}
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "验证码已失效");
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "密码找回失败");
	}

	/**
	 * 注册会员
	 * 
	 */
	@RequestMapping(value = "/reg")
	public @ResponseBody AjaxResult register(Users user, String uuid) {
		if (WebUtil.getSession().getAttribute(Dictionary.YZM) != null) { // 判断验证码是否失效
			if (user.getTel().equals(WebUtil.getSession().getAttribute(Dictionary.SJ))) { // 判断手机是否为发送短信的手机
				if (!(WebUtil.getRequest().getParameter(Dictionary.YZM))
						.equals(WebUtil.getSession().getAttribute(Dictionary.YZM))) // 判断验证码是否正确
				{
					return new AjaxResult(AjaxResult.STATUS_ERR, null, "验证码错误!");
				} else {
					// 判断手机是否以注册
					if (!userService.isOnlyPhone(user.getTel())) {
						// 密码加密
//						try {
//							user.setPassword(EncrypUtil.getMD5(user.getPassword()));
//						} catch (UnsupportedEncodingException e) {
//							e.printStackTrace();
//						}
						user.setRegisterTime(new Date());
						user.setUserType(Dictionary.USER_TYPE_CUSTIMER);
						user.setAccountStatus(Dictionary.ACCOUNT_STATUS_ACTIVATE);
						user.setValidateCode(UUID.randomUUID().toString().toUpperCase().replaceAll("-", ""));
						user.setIsDeleted("N");
						// 设置用户注册赠送金额
						user.setAge(Integer.parseInt(busParamService.findValueByCode(Dictionary.PARAM_CODE_ZCZS)));
						int i = userService.add(user);
						// 会员推荐码
						if (uuid != null && uuid.length() > 0) {
							Users tjuser = new Users();
							tjuser.setValidateCode(uuid);
							List<Users> tempUsers = userService.findByModel(tjuser);
							// 推荐用户存在
							if (tempUsers.size() == 1) {
								tjuser = tempUsers.get(0);
								// 推荐用户或者5个金币
								tjuser.setAge(tjuser.getAge() + 5);
								userService.modify(tjuser);
							}
						}
						if (i > 0) {
							// 自动登录
							WebUtil.getSession().setAttribute(SystemConstance.LOGIN_KEY, user);
							return new AjaxResult(AjaxResult.STATUS_OK, null, "会员注册成功");
						} else {
							return new AjaxResult(AjaxResult.STATUS_ERR, null, "会员注册失败");
						}
					} else {
						return new AjaxResult(AjaxResult.STATUS_ERR, null, "手机号已注册");
					}
				}
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "手机号未验证");
			}
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "验证码已失效");
		}

	}

}